package cn.itcast.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@WebServlet("/loginStudentServlet")
public class LoginStudentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //解决乱码问题
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        //获取表单数据
        String username = request.getParameter("username");
        String rememberme = request.getParameter("rememberme");

        //判断是否输入,若为null,则跳转回去
        if(username==null||"".equals(username)){
            response.sendRedirect(super.getServletContext().getContextPath()+"/login.jsp");
            return;
        }

        //读取web里data.txt文件
        InputStream is = super.getServletContext().getResourceAsStream("data.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        //判断用户名是否正确
        String line;
        while ((line=br.readLine())!=null){
            if(line.split(" ")[0].equalsIgnoreCase(username)){
                //如果正确,此时确定用户是否勾选自动登录
                if(rememberme!=null){
                    //若勾选,新建Cookie,名字为rememberme,值为当前时间
                    Cookie cookie = new Cookie("rememberme", String.valueOf(System.currentTimeMillis()));
                    //存在一小时,访问根路径为"/",
                    cookie.setMaxAge(60*60);
                    cookie.setPath("/");
                    //向浏览器中添加
                    response.addCookie(cookie);
                }
                //将用户名写入Attribute,并重定向
                request.getSession().setAttribute("username",username);
                response.sendRedirect(super.getServletContext().getContextPath()+"/index.jsp");
                return;
            }
        }

        //走到这里说明判断用户名为错误,直接转发
        request.setAttribute("error","新用户禁止登录");
        request.getRequestDispatcher("/login.jsp").forward(request,response);
    }
}













